﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pasys.PresentationCore;
using System.Collections.ObjectModel;
using UIShell.OSGi;

namespace Pasys.Document
{
    public class SystemSettingManager : ISettingManager
    {
        //private
        private ICommandBusService commandBus;
        private Dictionary<string, ISettingViewProvider> _providers = new Dictionary<string, ISettingViewProvider>();

        public List<ISettingViewProvider> AllSettingViewProviders
        {
            get
            {
                return _providers.Values.ToList();
            }
        }

        public SystemSettingManager()
        {
            commandBus = BundleRuntime.Instance.GetFirstOrDefaultService<ICommandBusService>();
            commandBus.SubscribeCommandEvent(CommandNames.Setting, Setting_Handler);

        }

        void Setting_Handler(object sender, object e)
        {
            SystemSetting st = new SystemSetting()
            {
                SystemSettings = this,
            };
            st.ShowDialog();
        }

        public List<ISettingViewProvider> GetSettingViewProviders()
        {
            return GetSettingViewProviders(string.Empty);
        }

        public List<ISettingViewProvider> GetSettingViewProviders(string parentKey)
        {
            var ps = _providers.Values.ToList().FindAll(m => m.ParentSettingKey.Equals(parentKey, StringComparison.CurrentCultureIgnoreCase));
            return ps;
        }

        public List<ISettingViewProvider> GetSettingViewProviders(ISettingViewProvider parentProvider)
        {
            if (parentProvider == null)
            {
                return GetSettingViewProviders(string.Empty);
            }
            else
            {
                return GetSettingViewProviders(parentProvider.SettingKey);
            }
        }


        public void UnRegister(ISettingViewProvider settingProvider)
        {
            if (!_providers.ContainsKey(settingProvider.SettingKey))
            {
                _providers.Remove(settingProvider.SettingKey);
            }
        }

        public void Register(ISettingViewProvider settingProvider)
        {
            if (string.IsNullOrEmpty(settingProvider.SettingKey))
            {
                _providers.Add(Guid.NewGuid().ToString(), settingProvider);
            }
            else if (!_providers.ContainsKey(settingProvider.SettingKey))
            {
                _providers.Add(settingProvider.SettingKey, settingProvider);
            }
        }
    }

}
